package com.yesin.listener;

import com.yesin.sms.SmsProperties;
import com.yesin.utils.SmsUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;

@Component
public class SmsListener {
    @Autowired
    private SmsUtils smsUtils;

    @Autowired
    private SmsProperties prop;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "YESHOP.SMS.QUEUE", durable = "true"),
            exchange = @Exchange(value = "YESHOP.SMS.EXCHANGE", ignoreDeclarationExceptions = "true"),
            key = {"sms.code"}))
    public void sendSms(Map<String, String> msg) throws Exception {
        if (CollectionUtils.isEmpty(msg)){
            return;
        }
        String phone = msg.get("phone");
        String code = msg.get("code");
        if (StringUtils.isNotBlank(phone) || StringUtils.isNotBlank(code)){
            // 发送消息
            this.smsUtils.sendSms(phone, code, this.prop.getSignName(), this.prop.getTemplateCode());
        }
    }
}
